#coding:utf8

'''
Created on 2016年6月11日

@author: zhangjinrui
'''
import matplotlib
from DataReader import DataReader
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.animation import FuncAnimation
import Tkinter as TK
from src.visual.NodeFigure import NodeFigure
import threading
import time
#全局变量 设定窗口与屏幕之间的距离
padding = 100;

path = '../../data'

class MainFrame:
    
    def __init__(self):
        
        self.tk = TK.Tk()
        self.figure_canvas = {}
        self.screen_width = self.tk.winfo_screenwidth()
        self.screen_height = self.tk.winfo_screenheight()
        self.width = self.screen_width - padding * 2;
        self.height = self.screen_height - padding * 2;
        
        self.dataReader = DataReader(path)
        self.figures = {}
        
        self.init_figures()
        self.add_figures_to_mainframe()
        
        button = TK.Button(master=self.tk, text="start", command = self.button_start)
        button.pack(side=TK.BOTTOM)
        
        button = TK.Button(master=self.tk, text="stop", command = self.button_stop)
        button.pack(side=TK.BOTTOM)
        
    def main(self):
        #设定主窗口的大小和位置，居中显示
        self.tk.geometry(str(self.width) + 'x' + str(self.height) + '+' + str(padding) + '+' + str(padding))
        self.tk.mainloop()
    
    def init_figures(self):
        self.hostnames = self.dataReader.get_hostnames()
        for h in self.hostnames:
            self.figures[h] = NodeFigure()
        self.figure_count = len(self.figures)
        
    def add_figures_to_mainframe(self):
        left_pad = 30
        each_pad = 10
        figure_width = (self.width - each_pad * (self.figure_count - 1) - left_pad * 2) / self.figure_count
        i = 0;
        for k,v in self.figures.items():
            self.add_one_figure(k, v, y = 10, x = left_pad + i * (each_pad + figure_width), w =figure_width, h = 0.7)
            i += 1
        
    def add_one_figure(self, hostname, nodeFigure, x, y , w, h):
        canvas = FigureCanvasTkAgg(nodeFigure.figure, master = self.tk)
        canvas.show()
        canvas.get_tk_widget().place(x = x, y = y, width = w, relheight = h )
        self.figure_canvas[hostname] = canvas
    
    def update_data(self):
        dat = self.dataReader.get_one_set_data()
        for k,figure in self.figures.items():
            figure.update_data(dat[k])
            (threading.Thread(target=self.figure_canvas[k].draw)).start()
#             self.figure_canvas[k].draw()
            
        self.timer1 = threading.Timer(1, self.update_data)
        self.timer1.start() 
    
    def button_start(self):
        self.update_data()
    
    def button_stop(self):
        self.timer1.cancel()
    
if __name__ == '__main__':
    mf = MainFrame()
    mf.main()
    
    
    
    
